﻿using CoreLocation;
using Futurism.Universal.Foundation;
using Futurism.Universal.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIKit;

namespace Fururism.Universal.Services.Mac
{
    [Export(typeof(ILocationService))]
    public class LocationService : ILocationService
    {
        private CLLocationManager locationManager;

        private List<ILocationAware> subscribers = null;

        private Location currentLocation;

        public LocationService()
        {
            this.locationManager = new CLLocationManager();
            // iOS 8 has additional permissions requirements
            //
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                locationManager.RequestAlwaysAuthorization(); // works in background
                //locMgr.RequestWhenInUseAuthorization (); // only in foreground
            }

            if (CLLocationManager.LocationServicesEnabled)
            {
                //set the desired accuracy, in meters
                locationManager.DesiredAccuracy = 1;
                locationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
                {
                    SetCurrentLocation(e.Locations[e.Locations.Length - 1]);

                    if (subscribers != null)
                    {
                        subscribers.ForEach(subscriber => subscriber.OnLocationUpdates(currentLocation));
                    }
                };

                locationManager.StartUpdatingLocation();
            }
        }

        public Location GetCurrentLocation()
        {
            return currentLocation;
        }

        private void SetCurrentLocation(CLLocation cLLocation)
        {
            currentLocation = new Location
            {
                Altitude = cLLocation.Altitude,
                Coordinate = new Coordinate
                {
                    Latitude = cLLocation.Coordinate.Latitude,
                    Longitude = cLLocation.Coordinate.Longitude
                },
                Course = cLLocation.Course,
                HorizontalAccuracy = cLLocation.HorizontalAccuracy,
                Speed = cLLocation.Speed,
                Timestamp = DateTime.Now,
                VerticalAccuracy = cLLocation.VerticalAccuracy
            };
        }

        public void RegisterForLocationUpdates(Futurism.Universal.Interfaces.ILocationAware locationAware)
        {
            this.subscribers.Add(locationAware);
        }

        public void UnregisterForLocationUpdates(Futurism.Universal.Interfaces.ILocationAware locationAware)
        {
            this.subscribers.Remove(locationAware);
        }
    }
}
